// 模块化路由
const express = require('express');
const router = express.Router();

// 引入模块
const path = require('path');
const fs = require('fs');
const time = require('time-stamp');
const session = require('cookie-session');
const svg = require('svg-captcha');

// 开启session功能
router.use(session({
    keys: ['']
}))

// 资源静态化
router.use(express.static(path.join(__dirname, 'public')));

// 接收post提交的参数
router.use(express.urlencoded({ extended: false }));

// 获取所有用户信息
let per = JSON.parse(fs.readFileSync(path.join(__dirname, '../persons.json')));

// 渲染页面
router.get('/register', (req, res) => {
    res.render('register');
})
router.get('/login', (req, res) => {
    res.render('login');
})

// 验证码
router.get('/code', (req, res) => {
    let captcha = svg.create();
    req.session.a = captcha.text;
    res.type('svg');
    res.send(captcha.data)
})

// 登录
router.post('/login', (req, res, next) => {
    user = req.body;
    let tag = per.some(item => item.username == user.username && item.password == user.password);
    if (tag) {
        next('登录成功');
    }
    else {
        next('账号或密码错误');
    }
})

// 注册
router.post('/register', (req, res, next) => {
    let user = req.body;

    if (!user.username || !user.password || !user.yzm) {
        next('请输入有效内容')
        return;
    }

    if (req.session.a.toLowerCase() != user.yzm.toLowerCase()) {
        next('验证码错误');
        return;
    }

    let tag = per.find(item => user.username == item.username);
    if (tag) {
        next('该用户已注册');
        return;
    }

    per.push({ username: user.username, password: user.password, time: time('YYYY年MM月DD日 HH:mm:ss') });
    fs.writeFileSync(path.join(__dirname, '../persons.json'), JSON.stringify(per));
    next('注册成功');
})

module.exports = router;